<?php
require_once BASE_PATH.'/db/database.php';

class User extends Database {

    //注册
    public function register($phone, $password, $pwd_confirm) {

        // 验证手机号格式
        if (!isValidPhoneNumber($phone)) {
            return json_encode(array('status'=>201,'message'=>'无效手机号！'));
        }


        // 密码确认
        if ($password !== $pwd_confirm) {
            return json_encode(array('status'=>201,'message'=>'两次输入密码不匹配！'));
        }

        if(strlen($password) < 6) {
            return json_encode(array('status'=>201,'message'=>'密码不得少于六位！'));
        }

        $sql = "SELECT * FROM user WHERE phone = '{$phone}';";
        $result = $this->getRow($sql);

        if ($result) {
            return json_encode(array('status'=>202,'message'=>'该手机号已被注册！'));
        }

        $user_id = generateUserId($phone);
        $nickname = generateNickname();
        $md5pwd = md5password($password);
        $blue_id = generateBlueId();
        $ip = getUserIpAsLong();
        $birthday = date('Y-m-d');
        $reg_time = time();

        $avatar = "/data/default_avatar/" . rand(1, 29) . ".jpg";

        $sql = "INSERT INTO user (user_id, nickname, avatar, phone, password, blue_id, birthday, u_type, ip, reg_time) VALUES ('{$user_id}', '{$nickname}', '{$avatar}', '{$phone}', '{$md5pwd}', $blue_id, '{$birthday}', 2, $ip, $reg_time)";

        try {
            $this->query($sql);
            return json_encode(array('status'=>200,'message'=>'用户注册成功！'));
        } catch (Exception $e) {
            return json_encode(array('status'=>201,'message'=>"注册失败: " . $e->getMessage()));
        }
    }

    public function login($phone, $password) {
        // 验证手机号格式
        if (!isValidPhoneNumber($phone)) {
            return json_encode(array('status'=>201,'message'=>'无效手机号！'));
        }

        $sql = "SELECT user_id,password FROM user WHERE phone = '{$phone}';";
        $json = json_decode($this->getRow($sql),true);
        $phonePwd = $json['password'];
        $uid = $json['user_id'];

        if ($phonePwd==md5password($password)){
            $ip = getUserIpAsLong();
            $updateIpSql = "UPDATE `user` SET `ip` = '{$ip}' WHERE `user`.`user_id` = '{$uid}';";
            $this->query($updateIpSql);

            $cookie = generateCookies($uid,$phone);
            return json_encode(array('status'=>200,'message'=>$cookie));
        }else{
            return json_encode(array('status'=>201,'message'=>'用户手机号或者密码错误！'));
        }

    }



    public function TempUidlogin($uid) {

        if (!isUid($uid)) {
            return json_encode(['status'=>201,'message'=>'uid error']);
        }

        $sql = "SELECT phone FROM user WHERE user_id = '{$uid}';";

        $phone = json_decode($this->getRow($sql),true)['phone'];

        if ($phone){
            $cookie = generateCookies($uid,$phone);
            return json_encode(array('status'=>200,'message'=>$cookie));
        }else{
            return json_encode(array('status'=>201,'message'=>'用户手机号或者密码错误！'));
        }

    }

    public function changepwd($uid, $password, $changepwd) {

        if (!isUid($uid)) {
            return json_encode(array('status'=>201,'message'=>'无效UID！'));
        }

        if(strlen($changepwd) < 6) {
            return json_encode(array('status'=>201,'message'=>'密码不得少于六位！'));
        }

        $sql = "SELECT password FROM user WHERE user_id = '{$uid}';";
        $json = json_decode($this->getRow($sql),true);
        $phonePwd = $json['password'];

        if ($phonePwd==md5password($password)){
            $changepwd = md5password($changepwd);   //加密修改的密码

            $updateSql = "UPDATE `user` SET `password` = '{$changepwd}' WHERE `user_id` = '{$uid}';";
            $this->query($updateSql);
;
            return json_encode(array('status'=>200,'message'=>'密码修改成功！'));
        }else{
            return json_encode(array('status'=>201,'message'=>'原密码错误！'));
        }

    }

    public function saveUserInfo($uid, $avatar, $nickname, $phone, $birthday, $blueid, $gender, $desc) {
        // 检查UID是否合法
        if (!isUid($uid)) {
            return json_encode(array('status' => 201, 'message' => '无效UID！'));
        }
        if ($gender != '0' && $gender != '1') {
            return json_encode(array('status' => 202, 'message' => '性别错误！'));
        }
        // 验证手机号格式
        if (!isValidPhoneNumber($phone)) {
            return json_encode(array('status'=>201,'message'=>'无效手机号！'));
        }

        // 检查手机号是否存在
        $checkPhoneSql = "SELECT COUNT(*) as count FROM user WHERE phone = '$phone' AND user_id != '{$uid}'";

        $phoneResult = json_decode($this->getRow($checkPhoneSql),true);

        if ($phoneResult['count'] > 0) {
            return json_encode(array('status' => 201, 'message' => '输入的手机号已存在！'));
        }
        // 检查蓝书号是否存在
        $checkBlueIdSql = "SELECT COUNT(*) as count FROM user WHERE blue_id = '$blueid' AND user_id != '{$uid}'";
        $blueIdResult = json_decode($this->getRow($checkBlueIdSql),true);
        if ($blueIdResult['count'] > 0) {
            return json_encode(array('status' => 201, 'message' => '输入的小蓝书号已存在！'));
        }


        $desc = daddslashes($desc);

        $sql = "
        UPDATE user 
        SET 
            avatar = '$avatar', 
            nickname = '$nickname', 
            phone = '$phone', 
            birthday = '{$birthday}', 
            blue_id = '{$blueid}', 
            gender = $gender, 
            description = '{$desc}' 
        WHERE 
            user_id = '{$uid}'
    ";

        $result = $this->query($sql);

        // 检查执行结果
        if ($result) {
            return json_encode(array('status' => 200, 'message' => '用户信息更新成功！'));
        } else {
            return json_encode(array('status' => 201, 'message' => '用户信息更新失败，请稍后重试！'));
        }
    }


    public function islogin($cookie)
    {
        $decookie = explode("_",aesDecrypt($cookie));
        $uid = $decookie[0];
        $phone  = $decookie[1];
        $overtime = $decookie[2];

        $current_time = time();

        if ($overtime < $current_time) {
            //echo "已超时\n";
            return json_encode(array('status'=>201,'message'=>'cookie已经过期！'));
        }

        // 验证手机号格式
        if (!preg_match('/^(1\d{10}|0\d{10})$/', $phone)) {
            return json_encode(array('status' => 202, 'message' => 'cookie无效手机号！'));
        }


        $sql = "SELECT * FROM user WHERE user_id = '{$uid}';";
        $result = json_decode($this->getRow($sql),true);
        if($result){
            return json_encode(array('status'=>200,'message'=>$result));
        }else{
            return json_encode(array('status'=>201,'message'=>'用户不存在！'));
        }


    }

    public function user_statistics($uid)
    {
        // 检查 uid 是否有效
        if (!isUid($uid)) {
            return json_encode(array('status' => 201, 'message' => 'uid 格式不正确！'));
        }

        $sql = "SELECT * FROM `user_statistics` WHERE `user_id` = '{$uid}'";

        $result = json_decode($this->getRow($sql));

        if ($result) {
            return json_encode(array('status' => 200, 'message' => $result));
        } else {
            $insertSql = "INSERT INTO `user_statistics` (`id`, `user_id`, `following_count`, `fans_count`, `likes_received_count`) VALUES (NULL, '{$uid}', '0', '0', '0');";
            $this->query($insertSql);
            $result = json_decode($this->getRow($sql),true);
            return json_encode(array('status' => 200, 'message' => $result));
        }

    }

    public function getAllUsers($page = 1, $limit = 12) {
        $offset = ($page - 1) * $limit;

        // 获取满足条件的评论的总数
        $countSql = "SELECT COUNT(*) as total FROM user";

        $total = json_decode($this->getRow($countSql),true)['total'];

        // 计算总页数
        $totalPages = ceil($total / $limit);

        $sql = "SELECT * FROM user ORDER BY reg_time DESC LIMIT $limit OFFSET $offset";

        $usersData = json_decode($this->getAll($sql), true);


        // 返回结果，包括评论数据、总页数和总记录数
        return [
            'totalPages' => $totalPages,
            'totalCount' => $total,
            'user' => $usersData,
        ];
    }

    public function getAllBotNum() {
        $countSql = "SELECT COUNT(*) as total FROM user where u_type=0";

        $total = json_decode($this->getRow($countSql),true)['total'];

        return $total;
    }

    public function getUsersGender() {
        // 获取所有用户的总数
        $countSql = "SELECT COUNT(*) as total FROM user";
        $total = json_decode($this->getRow($countSql), true)['total'];

        // 获取男性用户的数量
        $maleCountSql = "SELECT COUNT(*) as male_count FROM user WHERE gender = 1";
        $maleCount = json_decode($this->getRow($maleCountSql), true)['male_count'];

        // 获取女性用户的数量
        $femaleCountSql = "SELECT COUNT(*) as female_count FROM user WHERE gender = 0";
        $femaleCount = json_decode($this->getRow($femaleCountSql), true)['female_count'];

        // 计算比例
        $maleRatio = ($total > 0) ? ($maleCount / $total) * 100 : 0; // 男性比例
        $femaleRatio = ($total > 0) ? ($femaleCount / $total) * 100 : 0; // 女性比例

        // 返回结果
        return json_encode([
            'total' => $total,
            'male_count' => $maleCount,
            'female_count' => $femaleCount,
            'male_ratio' => round($maleRatio, 2),   // 男性比例（保留两位小数）
            'female_ratio' => round($femaleRatio, 2) // 女性比例（保留两位小数）
        ]);
    }


    public function upUserChecker($uid)
    {
        // 检查 uid 是否有效
        if (!isUid($uid)) {
            return json_encode(array('status' => 201, 'message' => 'uid 格式不正确！'));
        }
        $utypesql = "SELECT u_type FROM `user` WHERE `user_id` = '{$uid}'";
        $utype = json_decode($this->getRow($utypesql),true)['u_type'];
        if ($utype == 1) {
            return json_encode(array('status' => 201, 'message' => '管理员禁止申请审查官！'));
        }

        $sql = "UPDATE `user` SET `u_type` = '3' WHERE `user_id` = '{$uid}'";

        $this->query($sql);

        return json_encode(array('status' => 200, 'message' => '申请成功！'));

    }

    public function getUserFans($uid, $page = 1, $limit = 12)
    {
        // 检查 uid 是否有效
        if (!isUid($uid)) {
            return json_encode(array('status' => 201, 'message' => 'uid 格式不正确！'));
        }

        if($limit==575732022){  //粉丝男女比例数查询
            $sql = "SELECT 
                SUM(CASE WHEN u.gender = 1 THEN 1 ELSE 0 END) AS male_count, 
                SUM(CASE WHEN u.gender = 0 THEN 1 ELSE 0 END) AS female_count 
            FROM `fans` f
            LEFT JOIN `user` u ON f.fans_id = u.user_id
            WHERE f.user_id = '{$uid}'";
            $res = $this->getRow($sql);
            return $res;
        }

        $offset = ($page - 1) * $limit;

        // 构建 SQL 查询语句，使用 LIMIT 和 OFFSET 实现分页
        $sql = "
        SELECT f.fans_id,f.fans_time, u.nickname, u.avatar , u.ip  , u.blue_id  , u.birthday , u.gender 
        FROM `fans` f
        LEFT JOIN `user` u ON f.fans_id = u.user_id
        WHERE f.user_id = '{$uid}'
        ORDER BY fans_time DESC
        LIMIT {$limit} OFFSET {$offset}
        ";



        $result = $this->getAll($sql);

        return $result;

    }


    public function getUserFansTotal($uid, $limit = 12)
    {
        // 检查 uid 是否有效
        if (!isUid($uid)) {
            return json_encode(array('status' => 201, 'message' => 'uid 格式不正确！'));
        }


        // 构建 SQL 查询语句，使用 LIMIT 和 OFFSET 实现分页
        $countSql = "
        SELECT COUNT(*) as total FROM `fans` f 
        LEFT JOIN `user` u ON f.fans_id = u.user_id
        WHERE f.user_id = '{$uid}'
        LIMIT {$limit}
        ";


        $countResult = json_decode($this->getRow($countSql),true);
        $totalCount = $countResult ? $countResult['total'] : 0; // 获取总记录数
        return ceil($totalCount / $limit); // 计算总页码

    }

    public function getUserFollow($uid, $page = 1, $limit = 12)
    {
        // 检查 uid 是否有效
        if (!isUid($uid)) {
            return json_encode(array('status' => 201, 'message' => 'uid 格式不正确！'));
        }

        $offset = ($page - 1) * $limit;

        // 构建 SQL 查询语句，使用 LIMIT 和 OFFSET 实现分页
        $sql = "
        SELECT f.user_id,f.fans_time, u.nickname, u.avatar , u.ip  , u.blue_id  , u.birthday , u.gender 
        FROM `fans` f
        LEFT JOIN `user` u ON f.user_id = u.user_id
        WHERE f.fans_id = '{$uid}'
        ORDER BY fans_time DESC
        LIMIT {$limit} OFFSET {$offset}
        ";



        $result = $this->getAll($sql);

        return $result;

    }

    public function getUserFollowTotal($uid, $limit = 12)
    {
        // 检查 uid 是否有效
        if (!isUid($uid)) {
            return json_encode(array('status' => 201, 'message' => 'uid 格式不正确！'));
        }


        // 构建 SQL 查询语句，使用 LIMIT 和 OFFSET 实现分页
        $countSql = "
        SELECT COUNT(*) as total FROM `fans` f 
        LEFT JOIN `user` u ON f.user_id = u.user_id
        WHERE f.fans_id = '{$uid}'
        LIMIT {$limit}
        ";


        $countResult = json_decode($this->getRow($countSql),true);
        $totalCount = $countResult ? $countResult['total'] : 0; // 获取总记录数
        return ceil($totalCount / $limit); // 计算总页码

    }



    public function getUserLikeNum($nuid, $type)
    {
        // 检查 uid 是否有效
        if (!isUid($nuid)) {
            return json_encode(array('status' => 201, 'message' => 'uid 格式不正确！'));
        }
        if (!is_int($type)) {
            return json_encode(array('status' => 201, 'message' => 'type error！'));
        }

        $sql = "SELECT COUNT(*) as count FROM user_actions WHERE note_user_id = '{$nuid}' AND action_type = $type";

        $result = json_decode($this->getRow($sql),true)["count"];

        return $result;

    }

    public function getUserNoteNum($uid)
    {
        // 检查 uid 是否有效
        if (!isUid($uid)) {
            return json_encode(array('status' => 201, 'message' => 'uid 格式不正确！'));
        }

        $sql = "SELECT COUNT(*) as count FROM note WHERE user_id = '{$uid}'";

        $result = json_decode($this->getRow($sql),true)["count"];

        return $result;

    }

    public function updateUStatistLike($uid, $num)
    {
        // 检查 uid 是否有效
        if (!isUid($uid)) {
            return json_encode(array('status' => 201, 'message' => 'uid 格式不正确！'));
        }
        if (!is_int($num)) {
            return json_encode(array('status' => 201, 'message' => 'num error！'));
        }

        $sql = "UPDATE `user_statistics` SET `likes_received_count` = '{$num}' WHERE `user_id` = '{$uid}';";

        $this->query($sql);

        //eturn $result;

    }

    public function updateUStatistfans($uid, $num)
    {
        // 检查 uid 是否有效
        if (!isUid($uid)) {
            return json_encode(array('status' => 201, 'message' => 'uid 格式不正确！'));
        }
        if (!is_int($num)) {
            return json_encode(array('status' => 201, 'message' => 'num error！'));
        }

        $sql = "UPDATE `user_statistics` SET `fans_count` = '{$num}' WHERE `user_id` = '{$uid}';";

        $this->query($sql);


    }


    public function getUserType($uid)
    {
        // 检查 uid 是否有效
        if (!isUid($uid)) {
            return json_encode(array('status' => 201, 'message' => 'uid 格式不正确！'));
        }

        $sql = "select u_type from `user` WHERE `user_id` = '{$uid}';";

        return json_decode($this->getRow($sql),true)["u_type"];


    }

    public function addBot($num)
    {
        // 检查 $num 是否大于 100
        if ($num > 100) {
            return json_encode(array('status' => 201, 'message' => 'num error！'));
        }

        // 循环插入用户
        for ($i = 0; $i < $num; $i++) {
            // 随机生成手机号
            $phone = '0';
            for ($j = 0; $j < 10; $j++) {
                // 生成 0-9 之间的随机数字
                $phone .= rand(0, 9);
            }

            // 生成其他字段
            $user_id = generateUserId($phone);
            $nickname = generateNickname();
            $md5pwd = md5password('9911887');
            $gender = rand(0,1);
            $blue_id = generateBlueId();

            $ip = random_chinese_ip(); // 生成一个随机的 IPv4 地址整数

            $start = strtotime("1970-01-01"); // 起始日期
            $end = strtotime("2024-12-31");   // 结束日期
            $randomTimestamp = rand($start, $end);
            $birthday = date('Y-m-d', $randomTimestamp); // 将时间戳转换为日期
            $reg_time = time();
            $avatar = "/data/default_avatar/" . rand(1, 29) . ".jpg";


            $sql = "INSERT INTO user (user_id, nickname, avatar, phone, password, gender, blue_id, birthday, u_type, ip, reg_time) 
                VALUES ('{$user_id}', '{$nickname}', '{$avatar}', '{$phone}', '{$md5pwd}', '{$gender}', '{$blue_id}', '{$birthday}', 0, '{$ip}', '{$reg_time}')";

            $this->query($sql);
        }
    }

    public function randomBot($num)
    {
        // 检查 $num 是否大于 100
        if ($num > 100) {
            return json_encode(array('status' => 201, 'message' => 'num max 100 !'));
        }
        $num += 1;
        $numr2 = intval($num) * 2;
        $botSql = "SELECT user_id FROM user WHERE u_type = 0 ORDER BY RAND() LIMIT {$numr2}";

        $res = json_decode($this->getAll($botSql),true);

        if (!empty($res)) {
            $randomKeys = array_rand($res, min($num, count($res)));

            $randomResults = [];
            foreach ($randomKeys as $key) {
                $randomResults[] = $res[$key];
            }

            return $randomResults;
        } else {
            return json_encode(array('status' => 201, 'message' => 'no bot user'));
        }

    }

    public function upUserType($uid,$type)
    {
        // 检查 uid 是否有效
        if (!isUid($uid)) {
            return json_encode(array('status' => 201, 'message' => 'uid 格式不正确！'));
        }
        if ($type != 0 && $type != 1 && $type != 2 && $type != 3) {
            return json_encode(array('status' => 201, 'message' => '用户权限无效！'));
        }


        $sql = "select u_type from `user` WHERE `user_id` = '{$uid}';";

        $utype = json_decode($this->getRow($sql),true)['u_type'];
        /*if(!$utype){
            return json_encode(array('status' => 201, 'message' => 'UID不存在！'));
        }*/

        if($utype==1){
            return json_encode(array('status' => 201, 'message' => '禁止修改管理员权限！'));
        }

        $sql = "UPDATE `user` SET `u_type` = {$type} WHERE `user_id` = '{$uid}';";         //重置密码为123123

        $this->query($sql);

    }

    public function resetpwd($uid)
    {
        // 检查 uid 是否有效
        if (!isUid($uid)) {
            return json_encode(array('status' => 201, 'message' => 'uid 格式不正确！'));
        }

        $sql = "UPDATE `user` SET `password` = 'bf0fece0f144a205624ed3cb285f2120' WHERE `user_id` = '{$uid}';";         //重置密码为123123

        $this->query($sql);


    }

    public function delUser($uid)
    {
        // 检查 uid 是否有效
        if (!isUid($uid)) {
            return json_encode(array('status' => 201, 'message' => 'uid 格式不正确！'));
        }
        $sel_sql = "SELECT u_type FROM user WHERE user_id = '{$uid}'";
        $utype = json_decode($this->getRow($sel_sql),true)['u_type'];

        if($utype==1){
            return json_encode(array('status' => 201, 'message' => '禁止删除管理员！'));
        }


        $sql1 = "DELETE FROM `user` WHERE `user_id` = '{$uid}';";
        $sql2 = "DELETE FROM `user_statistics` WHERE `user_id` = '{$uid}';";
        $sql3 = "DELETE FROM `user_actions` WHERE `user_id` = '{$uid}';";
        $sql4 = "DELETE FROM `fans` WHERE `user_id` = '{$uid}';";
        $sql5 = "DELETE FROM `fans` WHERE `fans_id` = '{$uid}';";
        $sql6 = "DELETE FROM `comments` WHERE `user_id` = '{$uid}';";
        $note_sql = "UPDATE `note` SET `user_id` = '310da744a39058d3076ea7eb' WHERE `user_id` = '{$uid}';"; //修改userid为管理

        $this->query($sql1);
        $this->query($sql2);
        $this->query($sql3);
        $this->query($sql4);
        $this->query($sql5);
        $this->query($sql6);
        $this->query($note_sql);

    }

    public function searchUser($souid=null, $key, $page = 1, $limit = 12)
    {
        if (empty($key)) {
            return json_encode(array('status' => 201, 'message' => '搜索关键词不能为空！'));
        }
        if ($souid && !isUid($souid)){
            return json_encode(array('status' => 201, 'message' => 'uid error'));
        }

        $key = addslashes(htmlspecialchars($key, ENT_QUOTES, 'UTF-8'));

        $offset = ($page - 1) * $limit;

        $sqlExact = '';
        //$sqlFuzzy = '';

        // 判断关键词是否包含中文
        if (preg_match("/[\x{4e00}-\x{9fa5}]/u", $key)) {
            $sqlFuzzy = "
            SELECT u.user_id, u.nickname, u.avatar, u.blue_id 
            FROM `user` u
            WHERE u.`nickname` LIKE '%{$key}%'
        ";
        } else {
            if (preg_match("/^[a-zA-Z0-9]+$/", $key)) {
                $sqlExact = "
                SELECT u.user_id, u.nickname, u.avatar, u.blue_id 
                FROM `user` u
                WHERE u.`blue_id` = '{$key}'
            ";
            }

            // 模糊查询：nickname 和 blue_id 字段部分匹配关键词
            $sqlFuzzy = "
            SELECT u.user_id, u.nickname, u.avatar, u.blue_id 
            FROM `user` u
            WHERE (u.`nickname` LIKE '%{$key}%' OR u.`blue_id` LIKE '%{$key}%')
        ";
        }

        if ($sqlExact) {
            $sql = "({$sqlExact}) UNION ALL ({$sqlFuzzy}) LIMIT {$limit} OFFSET {$offset}";
        } else {
            $sql = "{$sqlFuzzy} LIMIT {$limit} OFFSET {$offset}";
        }

        $result = $this->getAll($sql);

        if (!$result) {
            return json_encode(array());
        }

        $userList = json_decode($result, true);

        $processedUserIds = [];
        // 获取用户统计数据并合并到用户列表
        foreach ($userList as $key => &$user) {
            // 如果user_id已经存在于processedUserIds中，移除该重复元素
            if (in_array($user['user_id'], $processedUserIds)) {
                unset($userList[$key]);
                continue;
            }

            $processedUserIds[] = $user['user_id'];

            $statistics = json_decode($this->user_statistics($user['user_id']), true);
            if ($statistics['status'] == 200) {
                $user['statistics'] = $statistics['message']; // 将统计信息添加到用户数据中
            } else {
                $user['statistics'] = null;
            }
            if (!empty($souid)) {
                $sql = "SELECT id FROM fans WHERE user_id = '{$user['user_id']}' AND fans_id = '{$souid}' LIMIT 1";
                $res = $this->getRow($sql);
                $user['isfans'] = !empty($res);
            } else {
                $user['isfans'] = false;
            }

            $note_num_sql = "SELECT count(*) FROM note WHERE user_id = '{$user['user_id']}'";
            $note_num_res = json_decode($this->getRow($note_num_sql),true)['count(*)'];
            $user['note_num'] = $note_num_res;
        }
        $userList = array_values($userList);
        return json_encode(array('status' => 200, 'message' => $userList));
    }




}

?>
